package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/middleware"
	"ginfast/pkg/dao"
	"ginfast/pkg/gctx"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Goods 商品
type Goods struct {
}

// ListHandler 列表
func (o *Goods) PageHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	var data []model.Goods
	total, _ := p.DbModelWhere(&model.Goods{}).Find(&data)
	gctx.JSONWrite(gin.H{"total": total, "rows": data}, c)
}

// GetHandler 查询
func (o *Goods) GetHandler(c *gin.Context) {
	dao.QueryByID(&model.Goods{}, c)
}

// AddHandler 新增
func (o *Goods) AddHandler(c *gin.Context) {
	var p model.Goods
	//获取参数
	if err := c.ShouldBind(&p.GoodsOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if p.OriginalPrice == nil {
		p.OriginalPrice = p.SalesPrice
	}
	if p.PromotionPrice == nil {
		p.PromotionPrice = p.SalesPrice
	}
	p.UpdatedBy = middleware.GetUserToken(c).UserName
	if err := dao.DbCreate(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// UpdateHandler 修改
func (o *Goods) UpdateHandler(c *gin.Context) {
	var p model.Goods
	//获取参数
	if err := c.ShouldBind(&p.GoodsOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	p.UpdatedBy = middleware.GetUserToken(c).UserName
	if err := dao.DbUpdateModel(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// DeleteHandler 删除
func (o *Goods) DeleteHandler(c *gin.Context) {
	dao.Deletes(&model.Goods{}, c)
}

// goodsspu/shelf?ids=1&shelf=1
// SspuShelfHandler 上架管理

type shelf struct {
	IDS   string `form:"ids"`
	Shelf string `form:"shelf"`
}

func (o *Goods) ShelfHandler(c *gin.Context) {
	var param shelf
	if err := c.ShouldBind(&param); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	ids := util.StringToIntSlice(param.IDS, ",")
	if err := dao.DbUpdateByIds(model.Goods{}, ids, dao.H{"shelf": param.Shelf}); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

func (o Goods) Routers(r *gin.RouterGroup) {
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.PUT("", o.UpdateHandler)
	r.POST("", o.AddHandler)
	r.DELETE("", o.DeleteHandler)
	r.PUT("/shelf", o.ShelfHandler)
}
